import 'dart:async';
import 'dart:io';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/update/common.dart';
import 'package:changxindianzishangwu/util/update/update_info_model.dart';
import 'package:changxindianzishangwu/util/update/update_prompter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_update_dialog/update_dialog.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'contacts/contacts_page.dart';
import 'find/find_page.dart';
import 'message/message_page.dart';
import 'my/my_page.dart';
import 'my/settings/bind_phone_page.dart';

class HomePage extends StatefulWidget {
  int pageIndex = 1;

  HomePage({Key key, this.pageIndex = 1}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var pageName = "HomePage:";
  var page;

  @override
  void initState() {
    _getInfo();
    checkUpdate();

    super.initState();
    // checkUpdate();

    currentIndex = widget.pageIndex;
    initialPage = widget.pageIndex;
    pageController = new PageController(initialPage: widget.pageIndex);
  }

  _getInfo() async {
    try {
      UserInfoModel userInfoModel = await UserInfoDao.getUserInfo();
      if (userInfoModel.resultCode == 0) {
        EcCache.getInstance().clear();
        showToast("请重新登录");
      Get.offAllNamed("/loginInit");
        return;
      }
    } catch (e) {
      EcCache.getInstance().clear();
      print("重新登陆：$e");
      showToast("请重新登录");
      Get.offAllNamed("/loginInit");
    }
  }

  bool flag = true;
  var tocken;
  var actionIcon = 0;
  int currentIndex;
  int initialPage;
  PageController pageController = new PageController();
  var nickName;

  // LoginStatusEnum f;

  @override
  Widget build(BuildContext context) {

    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize: Size(375, 812),
        orientation: Orientation.portrait);


    return Scaffold(
      body: PageView(
        controller: pageController,
        children: [
          MessagePage(),
          ContactsPage(),
          FindPage("${getUserId()}"),
          MyPage(),
          // ReportPage(),
        ],
        physics: NeverScrollableScrollPhysics(),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        onTap: (index) {
          setState(() {
            currentIndex = index;
            pageController.jumpToPage(index);
          });
        },
        selectedItemColor: Color.fromRGBO(0, 220, 169, 1),
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(
              icon: Stack(
                children: [
                  Image.asset(
                    currentIndex == 0
                        ? "images/bottom/消息-1.png"
                        : "images/bottom/消息-2.png",
                    fit: BoxFit.cover,
                    width: 16.w,
                    height: 16.w,
                  ),
                  // Positioned(
                  //     left: 10.w,
                  //     child: ClipOval(
                  //       child: Container(
                  //         width: 6.w,
                  //         height: 6.w,
                  //         color: Colors.red,
                  //         child: Text(""),
                  //       ),
                  //     ))
                ],
              ),
              label: "消息"),
          BottomNavigationBarItem(
              icon: Image.asset(
                currentIndex == 1
                    ? "images/bottom/联系人-1.png"
                    : "images/bottom/联系人-2.png",
                fit: BoxFit.cover,
                width: 16.w,
                height: 16.w,
              ),
              label: "联系人"),
          BottomNavigationBarItem(
              icon: Image.asset(
                currentIndex == 2
                    ? "images/bottom/动态-1.png"
                    : "images/bottom/动态-2.png",
                fit: BoxFit.cover,
                width: 16.w,
                height: 16.w,
              ),
              label: "发现"),
          BottomNavigationBarItem(
              icon: Image.asset(
                currentIndex == 3
                    ? "images/bottom/我的-1.png"
                    : "images/bottom/我的-2.png",
                fit: BoxFit.cover,
                width: 16.w,
                height: 16.w,
              ),
              label: "我的"),
        ],
      ),

    );
  }

  ///------------------------------更新APK start---------------------------------
  void checkPermission() async {
    ///权限申请
    Permission permission = Permission.storage;
    PermissionStatus status = await permission.status;
    print('检测权限$status');
    print('Permission 权限状态：$status');

    if (status.isGranted) {
      print(' Permission ：权限通过');
      // defaultStyle();
      //权限通过
    } else if (status.isDenied) {
      //权限拒绝， 需要区分IOS和Android，二者不一样
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      openAppSettings();
    } else if (status.isRestricted) {
      //活动限制（例如，设置了家长///控件，仅在iOS以上受支持。
      openAppSettings();
    } else {
      //第一次申请
      requestPermission(permission);
    }
  }

  void requestPermission(Permission permission) async {
    //发起权限申请
    PermissionStatus status = await permission.request();
    // 返回权限申请的状态 status
    if (status.isPermanentlyDenied) {
      openAppSettings();
    }
  }

  void checkUpdate() async {
    UpdateInfoModel _updateInfo = await UpLoadFileDao.checkVersion();
    if (_updateInfo.resultCode == 1) {
      String versionCode = await CommonUtils.getVersionCode();
      _updateInfo.data.isForce = false;

      int _zxVersionCODE = int.parse(versionCode);

      ///线上更新版本
      int _onlineCode = (Platform.isAndroid
          ? _updateInfo.data.androidVersion
          : _updateInfo.data.iosVersion);

      ///本地版本
      String _qzVersion = Platform.isAndroid
          ? _updateInfo.data.androidDisable
          : _updateInfo.data.iosDisable;

      ///强制更新版本
      print('--------强制更新 _zxVersionCODE$_zxVersionCODE');
      print('--------强制更新 _onlineCode$_onlineCode');
      print('--------强制更新 _qzVersion$_qzVersion');
      if (_zxVersionCODE < _onlineCode) {
        ///androidDisable 不等于空且 大于本地版本号 强制更新
        if (!ObjectUtil.isEmptyString(_qzVersion) &&
            int.parse(versionCode) < int.parse(_qzVersion)) {
          _updateInfo.data.isForce = true;
          UpdatePrompter(
              updateEntity: _updateInfo.data,
              onInstall: (String filePath) {
                CommonUtils.installAPP(filePath);
              }).show(context);
        }

        ///第一次新版本号 弹窗 然后保存版本号
        if (_onlineCode!= getVersionCode()) {
          setVersionCode(Platform.isAndroid
              ? _updateInfo.data.androidVersion
              : _updateInfo.data.iosVersion);
          UpdatePrompter(
              updateEntity: _updateInfo.data,
              onInstall: (String filePath) {
                CommonUtils.installAPP(filePath);
              }).show(context);
        }
      }
    }
  }

  ///------------------------------更新APK end---------------------------------
  ///用户没有绑定手机号 登录第一次进入这个页面提示他绑定手机号
  void _checkUserPhone(context )async  {
    String phone = getUserInfo().phone;
    if (ObjectUtil.isEmptyString(phone)) {
      await showCupertinoDialog(
          context: context, builder: (context) => getHintDialog(context));
    }
  }

  getHintDialog(BuildContext _context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(
                "提示",
                style:
                TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
              Text(
                AppString.bindingPhoneHint,
                style:
                TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
            ],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text(
              "取消",
              style: TextStyle(color: AppColor.colorGrey153),
            ),
            onPressed: () {
              Navigator.of(_context).pop();
            },
          ),
          CupertinoDialogAction(
            child: Text(
              "前去绑定",
              style: TextStyle(color: AppColor.colorTheme),
            ),
            onPressed: () {
              Get.to(BindPhonePage());
              Navigator.of(_context).pop();
            },
          ),
        ]);
  }
}
